package com.toocms.jinjuhang.ui.mine.management_system.vip_center

import android.app.Application
import android.os.Bundle
import android.text.TextUtils
import androidx.databinding.ObservableArrayList
import androidx.databinding.ObservableField
import com.blankj.utilcode.util.ActivityUtils
import com.blankj.utilcode.util.ResourceUtils
import com.blankj.utilcode.util.StringUtils
import com.toocms.jinjuhang.BR
import com.toocms.jinjuhang.R
import com.toocms.jinjuhang.config.Constants
import com.toocms.jinjuhang.config.Urls
import com.toocms.jinjuhang.config.UserRepository
import com.toocms.jinjuhang.data.center.OrganizationMemberData
import com.toocms.jinjuhang.widget.view_model.requestData
import com.toocms.tab.base.BaseModel
import com.toocms.tab.base.BaseViewModel
import com.toocms.tab.binding.ItemBinding
import com.toocms.tab.binding.command.BindingAction
import com.toocms.tab.binding.command.BindingCommand
import com.toocms.tab.bus.event.SingleLiveEvent
import com.toocms.tab.widget.picker.builder.TimePickerBuilder
import java.text.SimpleDateFormat
import java.util.Calendar

class VipListModel(application: Application, val bundle: Bundle?) :
    BaseViewModel<BaseModel>(application) {
    val dataFormat = SimpleDateFormat("yyyy-MM-dd")
    val calendar = Calendar.getInstance()
    var p = 1
    val defaultSortIconDrawable by lazy {
        ResourceUtils.getDrawable(R.mipmap.icon_arrow_top_bottom_gray)
    }
    val upSortIconDrawable by lazy {
        ResourceUtils.getDrawable(R.mipmap.icon_arrow_top_blue_bottom_gray)
    }
    val downSortIconDrawable by lazy {
        ResourceUtils.getDrawable(R.mipmap.icon_arrow_top_gray_bottom_blue)
    }
    var keywords: String? = null
        set(value) {
            field = value
            refresh()
        }
    val organizationId by lazy {
        bundle?.getString(Constants.BundleKey.KEY_ORGANIZATION_ID) ?: ""
    }
    val type by lazy {
        bundle?.getString(Constants.BundleKey.KEY_TYPE) ?: ""
    }
    val startTimeObservableField by lazy {
//        ObservableField(dataFormat.format(calendar.time))
        ObservableField<String>()
    }
    val endTimeObservableField by lazy {
//        ObservableField(dataFormat.format(calendar.time))
        ObservableField<String>()
    }
    val sortObservableField = ObservableField<VipSortType>()
    val loginNumberIconObservableField by lazy {
        ObservableField(defaultSortIconDrawable)
    }
    val orderNumberIconObservableField by lazy {
        ObservableField(defaultSortIconDrawable)
    }
    val getNumberIconObservableField by lazy {
        ObservableField(defaultSortIconDrawable)
    }
    val orderSumIconObservableField by lazy {
        ObservableField(defaultSortIconDrawable)
    }
    val loginNumberClickBindingCommand = BindingCommand<BindingAction>(BindingAction {
        when (sortObservableField.get()) {
            VipSortType.LOGIN_NUMBER_UP -> sortObservableField.set(VipSortType.LOGIN_NUMBER_DOWN)
            VipSortType.LOGIN_NUMBER_DOWN -> sortObservableField.set(VipSortType.LOGIN_NUMBER_UP)
            else -> sortObservableField.set(VipSortType.LOGIN_NUMBER_DOWN)
        }
        refreshIcon()
        refresh()
    })
    val orderNumberClickBindingCommand = BindingCommand<BindingAction>(BindingAction {
        when (sortObservableField.get()) {
            VipSortType.ORDER_NUMBER_UP -> sortObservableField.set(VipSortType.ORDER_NUMBER_DOWN)
            VipSortType.ORDER_NUMBER_DOWN -> sortObservableField.set(VipSortType.ORDER_NUMBER_UP)
            else -> sortObservableField.set(VipSortType.ORDER_NUMBER_DOWN)
        }
        refreshIcon()
        refresh()
    })
    val getNumberClickBindingCommand = BindingCommand<BindingAction>(BindingAction {
        when (sortObservableField.get()) {
            VipSortType.GET_NUMBER_UP -> sortObservableField.set(VipSortType.GET_NUMBER_DOWN)
            VipSortType.GET_NUMBER_DOWN -> sortObservableField.set(VipSortType.GET_NUMBER_UP)
            else -> sortObservableField.set(VipSortType.GET_NUMBER_DOWN)
        }
        refreshIcon()
        refresh()
    })
    val orderSumClickBindingCommand = BindingCommand<BindingAction>(BindingAction {
        when (sortObservableField.get()) {
            VipSortType.ORDER_SUM_UP -> sortObservableField.set(VipSortType.ORDER_SUM_DOWN)
            VipSortType.ORDER_SUM_DOWN -> sortObservableField.set(VipSortType.ORDER_SUM_UP)
            else -> sortObservableField.set(VipSortType.ORDER_SUM_DOWN)
        }
        refreshIcon()
        refresh()
    })
    val startTimeClickBindingCommand = BindingCommand<BindingAction>(BindingAction {
        selectedTime(1)
    })
    val endTimeClickBindingCommand = BindingCommand<BindingAction>(BindingAction {
        selectedTime(2)
    })


    val stopRefreshOrLoadSingleLiveEvent = SingleLiveEvent<Unit>()

    val refreshBindingCommand = BindingCommand<BindingAction>(BindingAction {
        refresh()
    })

    val loadBindingCommand = BindingCommand<BindingAction>(BindingAction {
        load()
    })

    val items = ObservableArrayList<VipListItemModel>()
    val itemBinding = ItemBinding.of<VipListItemModel>(BR.vipListItemModel, R.layout.item_vip_list)


    init {
        refresh(false)
    }


    /**
     * 选择时间
     *
     * @param type 1(开始时间),2(结束时间)
     */
    private fun selectedTime(type: Int) {
        TimePickerBuilder(
            ActivityUtils.getTopActivity()
        ) { date, v ->
            when (type) {
                1 -> {
                    startTimeObservableField.set(dataFormat.format(date))
                }
                2 -> {
                    endTimeObservableField.set(dataFormat.format(date))
                }
            }
            refresh()
        }.run {
            setTitleText(
                "${StringUtils.getString(if (1 == type) R.string.str_start else R.string.str_end)}${
                    StringUtils.getString(
                        R.string.str_date
                    )
                }"
            )
            setDividerColor(0x00000000)
            setLabel("", "", "", "", "", "")
            val startDate = startTimeObservableField.get()
            val endDate = endTimeObservableField.get()
            when (type) {
                1 -> {
                    if (!TextUtils.isEmpty(startDate)) {
                        calendar.time = dataFormat.parse(startDate)
                    }
                }
                2 -> {
                    if (!TextUtils.isEmpty(endDate)) {
                        calendar.time = dataFormat.parse(endDate)
                    }
                }
            }
            setDate(calendar)
            build()
        }.show()
    }

    private fun refreshIcon() {
        loginNumberIconObservableField.set(defaultSortIconDrawable)
        orderNumberIconObservableField.set(defaultSortIconDrawable)
        getNumberIconObservableField.set(defaultSortIconDrawable)
        orderSumIconObservableField.set(defaultSortIconDrawable)
        when (sortObservableField.get()) {
            VipSortType.LOGIN_NUMBER_DOWN -> loginNumberIconObservableField.set(downSortIconDrawable)
            VipSortType.LOGIN_NUMBER_UP -> loginNumberIconObservableField.set(upSortIconDrawable)
            VipSortType.ORDER_NUMBER_DOWN -> orderNumberIconObservableField.set(downSortIconDrawable)
            VipSortType.ORDER_NUMBER_UP -> orderNumberIconObservableField.set(upSortIconDrawable)
            VipSortType.GET_NUMBER_DOWN -> getNumberIconObservableField.set(downSortIconDrawable)
            VipSortType.GET_NUMBER_UP -> getNumberIconObservableField.set(upSortIconDrawable)
            VipSortType.ORDER_SUM_DOWN -> orderSumIconObservableField.set(downSortIconDrawable)
            VipSortType.ORDER_SUM_UP -> orderSumIconObservableField.set(upSortIconDrawable)
            else -> {}
        }
    }

    private fun refresh(isShowLoading: Boolean = false) {
        p = 1
        requestData(p, isShowLoading)
    }

    private fun load() {
        p++
        requestData(p)
    }

    private fun requestData(p: Int, isShowLoading: Boolean = false) {
        var url: String
        val params = mutableMapOf<String, String?>()
        params["member_id"] = UserRepository.user.member_id
        params["keywords"] = keywords
        params["start_time"] = startTimeObservableField.get()
        params["end_time"] = endTimeObservableField.get()
        params["sort"] = sortObservableField.get()?.code ?: ""
        params["p"] = p.toString()
        when (type) {
            Constants.Extra.IDENTITY_TYPE_ORGANIZATION -> {
                url = Urls.Center.ORGANIZATION_MEMBER
                params["organization_id"] = organizationId
            }
            else -> {
                url = Urls.Center.MEMBER_MEMBER
                params["parent_id"] = organizationId
            }
        }
        requestData(
            url = url,
            params,
            resultClass = OrganizationMemberData::class.java,
            isShowLoading = isShowLoading,
            result = {
                if (1 == p) items.clear()
                it.list?.forEach {
                    items += VipListItemModel(this@VipListModel, ObservableField(it))
                }
            },
            finish = {
                stopRefreshOrLoadSingleLiveEvent.call()
            })
    }

}